package cn.szzsi.business.service;

import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.common.util.MathUtil;
import cn.szzsi.model.*;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Service实现类 - 商户会员相关的service
 */
public class MemberService {

    public static final MemberService service = new MemberService();
    private static final String SYMOBL = ",";

    /**
     * 获取用户的二维码
     *
     * @param member
     * @return
     */
    public String getMemberQrcode(Member member) {
        return member.getStr("qrcode");
    }

    /**
     * 获取某人推荐的正式会员数目
     *
     * @param member
     * @return
     */
    public long getFormalRecommondNum(Member member) {
        long num = Db.queryColumn("select count(*) from sys_member where pid = ? and memberRank_id = ?", member.getStr("id"), "dafc86f6aee04a8aa9c722689ef65b3y");
        return num;
    }

    public boolean checkUserlogin(String username, String password) {
        long num = Db.queryColumn("select count(*) from sys_member where username = ? and password = ?", username, DigestUtils.md5Hex(password));
        if (num > 0)
            return true;
        else
            return false;
    }

    /**
     * 查看管理员是否存在
     */
    public boolean checkSysAdmin(String userName, String passWord) {
        long num = Db.queryColumn("select count(*) from sys_member where username = ? and password = ? and shopId = '-1'", userName, DigestUtils.md5Hex(passWord));
        if (num > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查看管理员是否存在
     */
    public boolean checkSysBusiness(String userName, String passWord) {
        long num = Db.queryColumn("select count(*) from sys_member where username = ? and password = ?", userName, DigestUtils.md5Hex(passWord));
        if (num > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 修改用户的直接上级
     *
     * @param m
     * @param pm
     */
    @Before(Tx.class)
    public String changeParent(Member m, Member pm) {
        String prepids = m.getStr("pids");
        m.set("pid", pm.getStr("id")).set("pids", pm.getStr("pids") + "," + pm.getStr("id")).update();

        List<Member> members = Member.dao.find("select * from sys_member where pids like '%" + m.getStr("id") + "%'");
        StringBuilder sb = new StringBuilder();
        sb.append("直接更改：")
                .append(m.getStr("username"))
                .append("->")
                .append(pm.getStr("username"))
                .append(",<br>被影响人员：");

        String tmpids = "";
        if (members != null && members.size() > 0) {
            for (Member mm : members) {
                tmpids = mm.getStr("pids");
                mm.set("pids", m.getStr("pids") + "," + StringUtils.substring(tmpids, tmpids.indexOf(m.getStr("id")), tmpids.length())).update();
                sb.append(mm.getStr("username")).append(StringUtils.SPACE);
            }
        }

        sb.append(",请检查推荐");
        return sb.toString();
    }



    /**
     * 用户菜单权限的V2版本
     *
     * @param shopId
     * @param member
     * @return
     */
    public void filterV2RoleResource(HttpServletRequest req, String shopId, Member member) {
        StringBuffer sb = new StringBuffer();

        //查询所有资源
        List<Resource> lbr1 = Resource.dao.getByUidAndLevel(shopId, 1);//一级菜单
        List<Resource> lbr2 = Resource.dao.getByUidAndLevel(shopId, 2);//二级菜单
        List<Resource> lbr3 = Resource.dao.getByUidAndLevel(shopId, 3);//三级菜单
        //根据角色来判断用户可以看到哪些资源
        List<RoleResource> lbrr = RoleResource.dao.getByRoleId(member.getStr("roleId"));

        String ranks = org.apache.commons.lang3.StringUtils.EMPTY;
        System.out.println("ranks------------"+ranks);
        for (RoleResource brr : lbrr) {
            ranks = ranks + "@" + brr.getStr("resourceId");
        }

        req.setAttribute("lbr1", lbr1);
        req.setAttribute("lbr2", lbr2);
        req.setAttribute("lbr3", lbr3);
        req.setAttribute("ranks", ranks);

    }

    /**
     * 根据角色和资源来判断该用户有什么权限的V1版本
     *
     * @param shopId
     * @param member
     * @return
     */
    public String filterRoleResource(String shopId, Member member) {

        //查询所有资源
        List<Resource> lbr = Resource.dao.getByUid(shopId);
        //根据角色来判断用户可以看到哪些资源
        List<RoleResource> lbrr = RoleResource.dao.getByRoleId(member.getStr("roleId"));

        String ranks = org.apache.commons.lang3.StringUtils.EMPTY;
        for (RoleResource brr : lbrr) {
            ranks = ranks + "@" + brr.getStr("resourceId");
        }

//		<li>
//            <a href="#">
//                <i class="fa fa fa-shopping-cart"></i>
//                <span class="nav-label">广告管理</span>
//                <span class="fa arrow"></span>
//            </a>
//            <ul class="nav nav-second-level">
//                <li><a class="J_menuItem" href="${base}/shop/adManage/list">广告管理</a></li>
//            </ul>
//        </li>
        StringBuffer sb = new StringBuffer();
        for (Resource br : lbr) {
            if (br.get("parent_id") == null) {//顶级
                if (!member.getStr("b_shoprank").equalsIgnoreCase("super"))
                    if (!org.apache.commons.lang3.StringUtils.contains(ranks, br.getStr("id")))
                        continue;
                sb.append("<li>");
                sb.append("<a href=\"" + br.getStr("url") + "\">");
                sb.append("<i class=\"fa fa " + br.getStr("icon") + "\"></i>");

                if (br.getStr("name").contains("-")) {
                    sb.append("<span class=\"nav-label\">" + br.getStr("name").split("-")[0] + "</span>");
                } else {
                    sb.append("<span class=\"nav-label\">" + br.getStr("name") + "</span>");
                }


                sb.append("<span class=\"fa arrow\"></span>");
                sb.append("</a>");
                if (lbr != null) {
                    sb.append("<ul class=\"nav nav-second-level\">");
                    for (Resource brr : lbr) {
                        if (!member.getStr("b_shoprank").equalsIgnoreCase("super"))
                            if (!org.apache.commons.lang3.StringUtils.contains(ranks, brr.getStr("id")))
                                continue;
                        if (brr.getStr("parent_id") != null && brr.getStr("parent_id").equalsIgnoreCase(br.getStr("id"))) {
                            if (brr.getStr("name").contains("-")) {
                                sb.append("<li><a class=\"J_menuItem\" href=\"" + brr.getStr("url") + "\">" + brr.getStr("name").split("-")[0] + "</a></li>");
                            } else {
                                sb.append("<li><a class=\"J_menuItem\" href=\"" + brr.getStr("url") + "\">" + brr.getStr("name") + "</a></li>");
                            }
                        }
                    }
                    sb.append("</ul>");
                }

                sb.append("</li>");
            }
        }
        return sb.toString();
    }


    public static void saveMemberInfo(String pid, String pids, String openid, String username, String sex, String country, String province, String city, String headimgurl, String privilege, String unionid, String shopId, String registerIp, String code,String date,Integer type,String sourceType) {
        Member member = new Member();
        member.set("pid", pid);
        member.set("pids", pids);
        member.set("openid", openid);
        if (StrKit.isBlank(sex)) {
            sex = "0";
        }
        member.set("sex", sex);
        member.set("country", country);
        member.set("province", province);
        member.set("city", city);
        member.set("headimgurl", headimgurl);
        member.set("privilege", privilege);
        member.set("unionid", unionid);
        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", openid);
        member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRank_id", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        if (StrKit.isBlank(registerIp)) {
            registerIp = "127.0.0.1";
        }
        member.set("registerIp", registerIp);
        member.set("loginIp", registerIp);
        if(StrKit.isBlank(date)){
            member.set("createDate", new Date());
        }else{
            member.set("createDate", date);
        }

        member.set("type",type);
        member.set("code", code);
        member.set("sourceType",sourceType);
        member.save();

    }


}
